package univer.oko.database.rmi.impl;

import univer.oko.Error;

import java.rmi.RemoteException;
import java.util.Vector;

/**
 * @author Eduard Dudar
 *         Date: 20.11.2005
 *         Time: 12:49:36
 */
public class FinancialItemImpl extends ImplHelper {
    public FinancialItemImpl(RMIImpl rmi) {
        super(rmi);
    }

    public synchronized int addFinUnit(String item, String faculty) throws RemoteException {
        if (this.isOccurs(
                "select [financial_item].[id_finitem] " +
                        "from [financial_item] " +
                        "where [financial_item].[finitem_name] = '" + item + "'")) {
            return univer.oko.Error.REPEAT;
        }

        int count = this.getIntValue("SELECT MAX(ID_FinItem) FROM Financial_Item") + 1;
        this.executeUpdate("INSERT INTO Financial_Item VALUES(" + count + ",'" + item + "'," + this.rmi.getFacultyID(faculty) + ")");
        this.commit();
        return Error.ALRIGHT;
    }

    public synchronized Vector getFinUnits() {
        return this.getVectorValue(
                "SELECT FinItem_Name " +
                        "FROM Financial_Item " +
                        "ORDER BY FinItem_Name");
    }

    public synchronized Vector getFinUnits(String str) {
        return this.getVectorValue(
                "SELECT FinItem_Name " +
                        "FROM Financial_Item, Faculty " +
                        "WHERE Financial_Item.Ref_Faculty = Faculty.ID_Faculty " +
                        "AND Faculty.Faculty_Name = '" + str + "'");
    }

    public synchronized int deleteFinUnit(String str) {
        boolean isOccurs = this.isOccurs(
                "SELECT Financial_Item.ID_FinItem " +
                        "FROM Financial_Item, Student " +
                        "WHERE Student.Ref_FinItem = Financial_Item.ID_FinItem " +
                        "AND Financial_Item.FinItem_Name = '" + str + "'");
        if (isOccurs) {
            return Error.IN_USE;
        }

        this.executeUpdate("DELETE FROM Financial_Item WHERE FinItem_Name = '" + str + "'");
        this.commit();
        return Error.ALRIGHT;
    }

    public synchronized Integer getFinUnitID(String str) {
        return this.getIntValue(
                "SELECT ID_FinItem " +
                        "FROM Financial_Item " +
                        "WHERE FinItem_Name = '" + str + "'");
    }

    public synchronized String getFinUnitName(int id) {
        return this.getStringValue(
                "SELECT FinItem_Name " +
                        "FROM Financial_Item " +
                        "WHERE ID_FinItem = " + id);
    }
}
